package com.button.boot.netty.client.netty;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.button.boot.netty.client.netty.channel.HelloWorldChannelInitializer;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

@Component
public class NettyClientApplication {
    private static final Logger LOGGER = LoggerFactory.getLogger(NettyClientApplication.class);

    public void start() {
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap()
                        .group(group)
                        // 该参数的作用就是禁止使用Nagle算法，使用于小数据即时传输
                        .option(ChannelOption.TCP_NODELAY, true)
                        .channel(NioSocketChannel.class)
                        .handler(new HelloWorldChannelInitializer());

        try {
            ChannelFuture future = bootstrap.connect("127.0.0.1", 8088).sync();
            LOGGER.info("客户端成功....");
            // 发送消息
            future.channel().writeAndFlush("你好啊");
            // 等待连接被关闭
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            LOGGER.error("初始化客户端时出现异常. ex={}", e);
        } finally {
            group.shutdownGracefully();
        }
    }
}
